/*
 * @Author: Turump 
 * @Date: 2021-03-31 11:00:21 
 * @Last Modified by: Turump
 * @Last Modified time: 2021-05-14 16:35:01
 * 播放音效
 */

import SoundHelper from "../helper/SoundHelper";
import { TaskBase } from "./TaskBase";

const { ccclass, property, menu } = cc._decorator;

@ccclass @menu("任务组件/播放音效")
export default class PlayAudioTask extends TaskBase {

    @property({ displayName: "完成Emit事件", tooltip: "任务完成Emit事件", override: true, visible: false })
    doneEvent = ""

    // @property({ displayName: "任务支持暂停", override: true, visible: false })
    // isPauseable = false;

    @property({ displayName: "重复任务", override: true, visible: false })
    repeatableTask = false;

    @property({ displayName: "音效", type: cc.AudioClip })
    audioClip: cc.AudioClip = null;

    @property({ displayName: "重复播放" })
    repeat = false;

    @property({ displayName: "间隔播放", visible() { return this.repeat } })
    repeatWithDuration = false;

    @property({ displayName: "播放间隔", visible() { return this.repeatWithDuration } })
    repeatDuration = 0;

    @property({ displayName: "是否为背景音乐" })
    isBGM = false;

    audioID = -1;
    enableTask() {
        super.enableTask();
        cc.log("PlayAudioTask enableTask:", this.audioClip.name)
        if (this.isBGM) {
            SoundHelper.getInstance().playBGM(this.audioClip);
        } else {
            this.playRepeatAudio();
        }
    }

    resmueTask() {
        super.resmueTask();
        cc.audioEngine.resume(this.audioID);
    }

    pauseTask() {
        super.pauseTask();
        cc.audioEngine.pause(this.audioID);
    }

    /**
     * 播放重复音效
     * 1. 直接一直重复
     * 2. 有间隔的重复
     */
    playRepeatAudio() {
        if (this.repeatWithDuration) {
            this.audioID = cc.audioEngine.play(this.audioClip, false, 1.0);
            this.scheduleOnce(this.playRepeatAudio.bind(this), this.repeatDuration);
            cc.log(`${this.name} playRepeatAudio with duration`)
        } else {
            this.audioID = cc.audioEngine.play(this.audioClip, this.repeat, 1.0);
        }
    }

    onDestroy() {
        cc.audioEngine.stopEffect(this.audioID);
        super.onDestroy()
    }
}
